package main

import (
	"flag"
	"log"
	"os"
	"os/signal"
	"strings"

	"manager/config"
	"manager/control"
	"manager/db"
	"manager/model"
	"manager/mqtt"

	"github.com/lerryxiao/gin"
	"hiscene.com/openplatform/common/logger"
)

var (
	version    string
	gitversion string
	cfgv       = flag.Bool("v", false, "show application version")
)

func init() {
	flag.Parse()
}

func main() {
	if *cfgv {
		log.Printf("%s %s\n", strings.TrimSpace(version), strings.TrimSpace(gitversion))
		return
	}

	logger.Log4gInit("conf/log4go.xml")
	defer func() {
		logger.Log4g.Close()
		db.Close()
	}()

	if config.Load() == false {
		logger.Log4g.Error("load config failed, exit")
		return
	}

	err := db.ConnectDB(config.Sqlfile)
	if err != nil {
		logger.Log4g.Error("connect db %v error: %v", config.Sqlfile, err)
		return
	}

	err = model.CheckTable(db.GetDB())
	if err != nil {
		logger.Log4g.Error("check table error: %v", err)
		return
	}

	err = control.Start()
	if err != nil {
		logger.Log4g.Error("control start error: %v", err)
		return
	}

	defer control.Stop()

	err = mqtt.Start()
	if err != nil {
		logger.Log4g.Error("mqtt start error: %v", err)
		return
	}

	defer mqtt.Stop()

	gin.SetMode(config.RunMode)

	go func() {
		ginRouter := gin.New()
		//ginRouter.RegPprof()
		control.SetRouter(ginRouter)
		ginRouter.Run(config.Server)
	}()

	signals := make(chan os.Signal, 1)
	signal.Notify(signals, os.Interrupt)
	for {
		select {
		case <-signals:
			{
				logger.Log4g.Trace("service shutdown by interupt")
				goto EXIT
			}
		}
	}
EXIT:
}
